import { ref, watch, Ref } from 'vue'

interface OptionsType {
  requestError?: () => void
  requestSuccess?: () => void
}

const useList = (
  listRequestFn: (params: Record<string, any>) => any,
  filterOption: Ref<Record<string, any>>,
  exportRequestFn?: (params: Record<string, any>) => any,
  options?: OptionsType
) => {
  // 加载状态
  const loading = ref(false)
  // 总数
  const totalNum = ref(0)
  // 每页数量
  const pageSize = ref(10)
  // 当前页码
  const pageNum = ref(1)
  // 列表数据
  const list = ref([])

  // 获取列表数据
  const loadData = async (page = pageNum.value) => {
    loading.value = true
    try {
      const res = await listRequestFn({
        pageSize: pageSize.value,
        pageNum: page,
        ...filterOption.value
      })
      list.value = res.data.list
      totalNum.value = res.data.totalNum
      options?.requestSuccess?.()
    } catch (error) {
      options?.requestError?.()
      console.log('请求出错了', 'error')
    } finally {
      loading.value = false
    }
  }

  // 重置
  const reset = () => {
    if (!filterOption.value) return
    const keys = Reflect.ownKeys(filterOption.value)
    filterOption.value = {}
    keys.forEach(key => {
      Reflect.set(filterOption.value, key, undefined)
    })
    loadData()
  }

  // 下载文件流
  const getDownloadFile = (data, name?) => {
    name = name || '下载.xls'
    const url = window.URL.createObjectURL(new Blob([data]))
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', name)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  // 导出
  const exportFile = async () => {
    if (!exportRequestFn) {
      throw new Error('当前没有提供exportRequestFn函数')
    }
    try {
      const res = await exportRequestFn(filterOption.value)
      getDownloadFile(res.data)
    } catch (error) {
      console.log('导出失败', 'error')
    }
  }

  // 监听分页数据变化
  watch([() => pageNum.value, () => pageSize.value], () => {
    loadData(pageNum.value)
  })

  return {
    totalNum,
    pageNum,
    pageSize,
    list,
    reset,
    exportFile,
    loadData
  }
}

export default useList
